/*
 * Copyright (c) 2010-2011 Josef Hardi <josef.hardi@gmail.com>
 * Copyright (c) 2010 Piotr Zagawa <piotr.zagawa@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package id.duapuluhdua.dakidaki.activities;

import android.location.Location;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

import id.duapuluhdua.dakidaki.Command;
import id.duapuluhdua.dakidaki.MainDraw;
import id.duapuluhdua.dakidaki.MainThread;
import id.duapuluhdua.dakidaki.MainView;
import id.duapuluhdua.dakidaki.R;
import id.duapuluhdua.dakidaki.Request;
import id.duapuluhdua.dakidaki.Utils;
import id.duapuluhdua.dakidaki.common.CommonActivity;
import id.duapuluhdua.dakidaki.data.common.DataTableOperation;
import id.duapuluhdua.dakidaki.data.tables.DataTableTracks;
import id.duapuluhdua.dakidaki.gps.GpsActivityReader;
import id.duapuluhdua.dakidaki.loader.DataLoader;
import id.duapuluhdua.dakidaki.service.ServiceCommand;

/**
 * Called when the activity is first created.
 */
public class ActivityMain extends CommonActivity
{
  /** Fields */
  private static String appVersion;
  private static ActivityMain self;
  private static GpsActivityReader gpsReader;

  private MainView mMainView;
  private MainThread mMainThread;

  public static DataLoader loader;

  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);

    ActivityMain.self = this;
    setContentView(R.layout.activity_main);

    // Get the application version
    appVersion = Utils.getAppVersion(this);

    // Set service context
    ServiceCommand.init(this);

    // Initialize global commands
    Command.init(this);

    // Create data container
    loader = new DataLoader(this);

    // Create activity GPS reader
    gpsReader = new GpsActivityReader(this, mPreference);

    // Get handle to the View from XML
    mMainView = (MainView)findViewById(R.id.MainView);

    // Initialize and prepare thread
    mMainView.init(this);

    // Get thread handle
    mMainThread = mMainView.getThread();

    // Create main thread
    mMainThread.createThread();

    // Restore thread state
    mMainThread.restoreState(savedInstanceState);

    loader.loadData();

    // Start service
    ServiceCommand.send(ServiceCommand.CMD_START_SERVICE);

    // Get current location
    gpsReader.restart();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu)
  {
    boolean result = super.onCreateOptionsMenu(menu);

    Command.addMenuItem(menu, Command.CMD_PREFERENCES, R.drawable.ic_menu_preferences);
    Command.addMenuItem(menu, Command.CMD_TRACK_HISTORY, R.drawable.ic_menu_history);
    Command.addMenuItem(menu, Command.CMD_ABOUT, R.drawable.ic_menu_about);

    return result;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item)
  {
    final int menuId = item.getItemId();
    Request data = new Request(Request.MODE_NONE);

    return mAction.run(menuId, data);
  }

  @Override
  protected void onStart()
  {
    super.onStart();

    if (!gpsReader.isStarted()) {
      gpsReader.start();
    }
  }

  @Override
  protected void onResume()
  {
    super.onResume();
  }

  @Override
  protected void onPause()
  {
    super.onPause();

    mMainThread.setEnabled(false);  // pause the main thread
  }

  @Override
  protected void onStop()
  {
    super.onStop();

    MainDraw.compassRotation.disable();  // stop reading the compass
  }

  @Override
  protected void onDestroy()
  {
    // Destroy main thread
    mMainThread.destroyThread();

    // Stop getting current location
    gpsReader.forceStop();

    // Stop reading compass
    MainDraw.compassRotation.disable();

    super.onDestroy();
  }

  @Override
  protected void onSaveInstanceState(Bundle outState)
  {
    super.onSaveInstanceState(outState);

    // Save thread state
    mMainThread.saveState(outState);
  }

  @Override
  public void onWindowFocusChanged(boolean hasWindowFocus)
  {
    if (hasWindowFocus) {
      mMainThread.setEnabled(true);
    }
    else {
      mMainThread.setEnabled(false);
    }
  }

  /** Handles "Map Mode" click */
  public void onMapModeClick(View v)
  {
    mAction.run(Command.CMD_MODE_MAP, null);
  }

  /** Handles "Track Mode" click. */
  public void onTrackModeClick(View v)
  {
    mAction.run(Command.CMD_MODE_TRACKS, null);
  }

  /** Handles "Info Mode" click. */
  public void onInfoModeClick(View v)
  {
    mAction.run(Command.CMD_MODE_INFO, null);
  }

  /** Handles "Play Mode" click. */
  public void onTrackPlayClick(View v)
  {
    ImageButton button = (ImageButton) v;
    if (button.isSelected()) {
      Toast.makeText(mContext, "Pause tracking", Toast.LENGTH_SHORT).show();

      // Change to RESUME image.
      button.setSelected(false);
      button.setImageResource(R.drawable.ic_track_play);
    }
    else {
      mAction.run(Command.CMD_TRACK_START, null);
      Toast.makeText(mContext, "Start/resume tracking", Toast.LENGTH_SHORT).show();

      // Change to PAUSE image.
      button.setSelected(true);
      button.setImageResource(R.drawable.ic_track_pause);
    }
  }

  public MainView getView()
  {
    return mMainView;
  }

  /**
   * Retrieves the version of TrekJournal.
   *
   * @return The version number.
   */
  public static String getAppVersion()
  {
    return appVersion;
  }

  /**
   * @return
   */
  public static Location getLastLocation()
  {
    if (gpsReader == null) {
      return null;
    }
    return gpsReader.getLastLocation();
  }

  /**
   *
   */
  public static void restartGPS()
  {
    gpsReader.restart();
  }

  /**
   *
   * @param op
   * @param tableName
   */
  public static void onChangeTableState(DataTableOperation op, String tableName)
  {
    // If tracks table
    if (DataTableTracks.tableName.equals(tableName)) {
      if (op.operation != DataTableOperation.OP_NONE)
        self.mState.update();

      // Update track
      if (op.operation == DataTableOperation.OP_UPDATE) {
        // Select open track
        ActivityMain.loader.selectOpenTrack();

        // Select location if recording resume
        if (op.command == ServiceCommand.CMD_TRACK_RECORDING_RESUME) {
          ActivityMain.loader.selectLocation();
        }
      }

      // Insert track
      if (op.operation == DataTableOperation.OP_INSERT) {
        ActivityMain.loader.selectOpenTrack();
        ActivityMain.loader.selectLocation();
      }

      // Delete track
      if (op.operation == DataTableOperation.OP_DELETE) {
        ActivityMain.loader.clearTrackSelection();
      }
    }
  }
}